var flag = false;
var InvestorModule = function () {
    var editable = function () {
        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":false,
                    "displayLength": 10,
                    "scrollX": true,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [0]
						},
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [1]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [2]
						}
                    ],
                    "columns": [
                       { "data": "name" },
                       { "data": "uploadTime" },
                       { "data": "operter" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/investor/riskListQuery",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   nRow.children[0].url = aData.url;
                	   nRow.children[0].name = aData.name;
                	   $('td:eq(0)', nRow).html(aData.name);
                	   var uploadTime = aData.uploadTime
                	   if(uploadTime == null){
                		   $('td:eq(6)', nRow).html('-'); 
                	   }else{
                		   uploadTime = uploadTime.substr(0, 10)
                		   $('td:eq(1)', nRow).html(uploadTime); 
                	   }
                	   $('td:eq(2)', nRow).html('<a class="modify fa fa-pencil fa-lg " title="修改" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="delete fa fa-times-circle-o fa-lg" title="删除" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="detail fa fa-bars fa-lg" title="详情" href="javascript:;"></a>');
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "{";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   json = json + ',"type":0}';
                       $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                //修改风险揭示书
                $('#modelEditable').on("click", "a.modify", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var name = nRow.children[0].name
                    $("#modify_Modal_btn").click();
                    $("#modify_riskDisclosureName").html(name);
                    $("#modify_riskDisclosureId").html(id);
                    $("#modify_riskDisclosureFile").val("");
                }));
                //删除风险揭示书
                $('#modelEditable').on("click", "a.delete", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var o =  nRow.children[0];
                    var id = nRow.children[0].id;
                    $.teninedialog({
                        title:'系统提示',
                        content:'确认删除此风险揭示书吗？',
                        showCloseButton:false,
                        otherButtons:["确定","取消"],
                        otherButtonStyles:['btn-primary','btn-white'],
                        bootstrapModalOption:{keyboard: true},
                        clickButton:function(sender,modal,index){
                       	if(index == 0){
                                $.ajax({
                                	type:"post",
                                    contentType:"application/json; charset=UTF-8",
                                    url: ctx + "/investor/delRiskDisclosure/"+id,
                                    dataType:"json",
                                    success: function(msg){
                                   	 $.teninedialog({
                                            title:'系统提示',
                                            content:msg.message,
                                            showCloseButton:false,
                                            otherButtons:["确定"],
                                            otherButtonStyles:['btn-primary'],
                                            bootstrapModalOption:{keyboard: true},
                                            clickButton:function(sender,modal,index){
                                            	location.reload();
                                            }
                                        });
                                    },
                                    error: function (msg) {
                                    	bootbox.alert("服务器出错了,删除风险揭示书失败了!");
                                    }
                                });
                       	 }
                       	 $(this).closeDialog(modal); 
                        }
                    });
                }));
                //查看风险揭示书详情
                $('#modelEditable').on("click", "a.detail", (function (e) {
                	 e.preventDefault();
                     var nRow = $(this).parents('tr')[0];
                     var id = nRow.children[0].id;
                     window.location.href = ctx +"/investor/riskDisclosure?riskDisclosureId="+id;
                     return;
                }));
                
                //下载风险揭示书
                $('#modelEditable').on("click", "a.down", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var o =  nRow.children[0];
                    var riskDisclosure = nRow.children[0].riskDisclosure;
                    var orderId = nRow.children[0].orderId;
                    $.ajax({
                    	type:"post",
                        contentType:"application/json; charset=UTF-8",
                        url: ctx +"/investor/checkRiskDisclosure",
                        dataType:"json",
                        success: function(msg){
                        	if(msg.code == 1){
                        		 if(riskDisclosure != undefined && riskDisclosure != ""){
                                 	window.location.href = ctx +"/orders/downloadFile?filePath="+riskDisclosure;	
                                 }else{
                                 	//如果风险揭示书未生成，则先生成之后保存风险揭示书路径并提供下载
                                	 window.location.href = ctx +"/investor/createRiskDisclosure/"+orderId;
                                 }
                        		
                        	}else if (msg.code == 0){
                        		bootbox.alert("请先设置风险揭示书模板.");
                        	}
                        },
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                }));
                $('#btn_query').click(function(){
                	oTable.fnClearTable();
                });
            }

        };
    }();
    return {
        init: function () {
        	editable.init();
        	//handleResourceTree();
        }
    };
}();

function uploadRiskDisclosure() {
	if (!$("#riskDisclosureFile").val()) {
		return;
	}
	$.ajaxFileUpload({
			url : ctx + '/investor/upload',
			type : 'post',
			secureuri : false,
			fileElementId : 'riskDisclosureFile',
			dataType : 'json',
			success : function(data, status) {
				if (data.code == 1) {
					$("#riskDisclosure").text(data.data.riskDisclosure.match(/[^\\/]*$/)[0]);
					$("#reviewRiskDisclosure").attr("onclick","javascript:location.href='investor/downloadEffect'");
					$("#riskDisclosureDiv").css("display", "");
					$('#dsimiss_deal_emp').click();
					$.teninedialog({
                        title:'系统提示',
                        content:'上传风险揭示书成功！',
                        showCloseButton:false,
                        otherButtons:["确定"],
                        otherButtonStyles:['btn-primary'],
                        bootstrapModalOption:{keyboard: true},
                        clickButton:function(sender,modal,index){
                        	location.reload();
                        }
                    });
				} else {
					bootbox.alert("上传失败！");
				}
		},
		error : function(msg, status, e) {
			bootbox.alert("上传失败！");
		}
	});
}

function modifyRiskDisclosure(){
	if (!$("#modify_riskDisclosureFile").val()) {
		bootbox.alert("上传文件不能为空");
		return;
	}
	var id = $("#modify_riskDisclosureId").html();
	if(id == ""){
		bootbox.alert("修改风险揭示书出错.");
		return;
	}
	//上传文件
	$.ajaxFileUpload({
			url : ctx + '/investor/modifyDisclosureFile',
			type : 'post',
			secureuri : false,
			fileElementId : 'modify_riskDisclosureFile',
			dataType : 'json',
			data: {'id':id},
			success : function(data, status) {
				if (data.code == 1) {
					$('#dsimiss_deal_emp').click();
					$.teninedialog({
                        title:'系统提示',
                        content:'修改风险揭示书成功！',
                        showCloseButton:false,
                        otherButtons:["确定"],
                        otherButtonStyles:['btn-primary'],
                        bootstrapModalOption:{keyboard: true},
                        clickButton:function(sender,modal,index){
                        	location.reload();
                        }
                    });
				} else {
					bootbox.alert("修改风险揭示书失败！");
				}
			},
			error : function(msg, status, e) {
				bootbox.alert("上传失败！");
			}
	});
}

$("#investorName").autocomplete({
    source: function(query,process){
    	$.ajax({
        	"contentType":"application/json; charset=UTF-8",
            "dataType" : 'json',
            "type" : "POST",
            "url" : ctx + "/appointment/investor/"+query.term,
            "data" : {"matchCount":200},
            "success" : function(data){
            	var ebean = [];
            	var length = data.length >= 10 ? 10 : data.length;
            	for (var int = 0; int < length; int++) {
            		var temp = [];
            		temp.label = data[int].name;
            		temp.name = data[int].name;
            		temp.value = data[int].name;
            		ebean.push(temp);
        		}
                return process(ebean);
            }
        })
    },
    search:function(event, ui){
    },
    select: function(event, ui) {
        $("#investorName").val(ui.item.name);
        var uistr =ui.item;
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});
$("input#investorName").focus(function(){
	$(this).autocomplete("search", "TOTAL");
	event.preventDefault(); 
});
$("input#investorName").blur(function(){
	event.preventDefault(); 
});

$("#employeeName").autocomplete({
    source: function(query,process){
    	$.ajax({
        	"contentType":"application/json; charset=UTF-8",
            "dataType" : 'json',
            "type" : "POST",
            "url" : ctx + "/orders/employee/"+query.term,
            "data" : {"matchCount":200},
            "success" : function(data){
            	var ebean = []
            	var length = data.length >= 10 ? 10 : data.length;
            	for (var int = 0; int < length; int++) {
            		var temp = [];
            		temp.label = data[int].employeeName;
            		temp.value = data[int].employeeName;
            		ebean.push(temp);
        		}
                return process(ebean);
            }
        })
    },
    search:function(event, ui){
    	console.log("searched!");
    },
    select: function(event, ui) {
        $("#employeeName").val(ui.item.label);
        var uistr =ui.item;
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});
$("input#employeeName").focus(function(){
	$(this).autocomplete("search", "TOTAL");
	event.preventDefault(); 
});
$("input#employeeName").blur(function(){
	event.preventDefault(); 
});

$("#productBriefName").autocomplete({
    source: function(query,process){
    	$.ajax({
        	"contentType":"application/json; charset=UTF-8",
            "dataType" : 'json',
            "type" : "POST",
            "url" : ctx + "/orders/product/"+query.term +"/0",
            "data" : {"matchCount":200},
            "success" : function(data){
            	var ebean = []
            	var length = data.length >= 10 ? 10 : data.length;
            	for (var int = 0; int < length; int++) {
            		var temp = [];
            		temp.label = data[int].briefName;
            		temp.value = data[int].briefName;
            		ebean.push(temp);
        		}
                return process(ebean);
            }
        })
    },
    search:function(event, ui){
    },
    select: function(event, ui) {
        $("#productBriefName").val(ui.item.label);
        var uistr =ui.item;
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});
$("input#productBriefName").focus(function(){
	$(this).autocomplete("search", "TOTAL");
	event.preventDefault(); 
});
$("input#productBriefName").blur(function(){
	event.preventDefault(); 
});

function downloadEffect(){
	//javascript:location.href='investor/downloadEffect'
}
